// 全局变量
let temperatureChart, energyChart;
let lastUpdateTime = new Date();

// 全局数据存储
let trainData = {
    weight: {
        a1: 0,
        b1: 0,
        b2: 0,
        a2: 0
    },
    clock: {
        year: 2024,
        month: 1,
        day: 1,
        hour: 0,
        minute: 0,
        second: 0
    },
    air_consumption: {
        driver_cab: 0.0,
        a1: 0.0,
        b1: 0.0,
        b2: 0.0,
        a2: 0.0,
        tail_driver_cab: 0.0,
        total: 0.0
    },
    temp_humi: {
        a1: { temp: 22, humidity: 45, outdoor_temp: 15, pm25: 25, pmtovc: 30, co2: 400 },
        b1: { temp: 23, humidity: 48, outdoor_temp: 15, pm25: 28, pmtovc: 32, co2: 420 },
        b2: { temp: 21, humidity: 42, outdoor_temp: 15, pm25: 22, pmtovc: 28, co2: 380 },
        a2: { temp: 24, humidity: 50, outdoor_temp: 15, pm25: 30, pmtovc: 35, co2: 450 }
    },
    valves: {
        a1: { room_temp: 22, return_air_temp: 20, fresh_air_temp: 18, status: 0xFFFF },
        b1: { room_temp: 23, return_air_temp: 21, fresh_air_temp: 19, status: 0xFFFF },
        b2: { room_temp: 21, return_air_temp: 19, fresh_air_temp: 17, status: 0xFFFF },
        a2: { room_temp: 24, return_air_temp: 22, fresh_air_temp: 20, status: 0xFFFF }
    },
    is_energy_saving: false
};

// 图表数据
let chartData = {
    temperature: {
        labels: [],
        a1: [],
        b1: [],
        b2: [],
        a2: []
    },
    energy: {
        labels: [],
        total: [],
        a1: [],
        b1: [],
        b2: [],
        a2: []
    }
};

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    updateDisplay();
    startRealTimeUpdates();
    updateClock();
    setInterval(updateClock, 1000);
});

// 初始化图表
function initializeCharts() {
    // 温度趋势图
    const tempCtx = document.getElementById('temperatureChart').getContext('2d');
    temperatureChart = new Chart(tempCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: 'A1车厢',
                    data: [],
                    borderColor: '#ff0066',
                    backgroundColor: 'rgba(255, 0, 102, 0.1)',
                    tension: 0.4,
                    borderWidth: 3,
                    pointRadius: 4,
                    pointHoverRadius: 6
                },
                {
                    label: 'B1车厢',
                    data: [],
                    borderColor: '#00ffff',
                    backgroundColor: 'rgba(0, 255, 255, 0.1)',
                    tension: 0.4,
                    borderWidth: 3,
                    pointRadius: 4,
                    pointHoverRadius: 6
                },
                {
                    label: 'B2车厢',
                    data: [],
                    borderColor: '#ffaa00',
                    backgroundColor: 'rgba(255, 170, 0, 0.1)',
                    tension: 0.4,
                    borderWidth: 3,
                    pointRadius: 4,
                    pointHoverRadius: 6
                },
                {
                    label: 'A2车厢',
                    data: [],
                    borderColor: '#0080ff',
                    backgroundColor: 'rgba(0, 128, 255, 0.1)',
                    tension: 0.4,
                    borderWidth: 3,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        color: '#00ffff',
                        font: {
                            size: 14
                        }
                    }
                }
            },
            scales: {
                x: {
                    ticks: {
                        color: '#b0b8c1'
                    },
                    grid: {
                        color: 'rgba(0, 255, 255, 0.1)'
                    }
                },
                y: {
                    beginAtZero: false,
                    title: {
                        display: true,
                        text: '温度 (°C)',
                        color: '#00ffff'
                    },
                    ticks: {
                        color: '#b0b8c1'
                    },
                    grid: {
                        color: 'rgba(0, 255, 255, 0.1)'
                    }
                }
            }
        }
    });

    // 能耗分析图
    const energyCtx = document.getElementById('energyChart').getContext('2d');
    energyChart = new Chart(energyCtx, {
        type: 'bar',
        data: {
            labels: ['司机室', 'A1', 'B1', 'B2', 'A2', '尾端司机室'],
            datasets: [{
                label: '能耗 (kW·h)',
                data: [0, 0, 0, 0, 0, 0],
                backgroundColor: [
                    'rgba(255, 0, 102, 0.8)',
                    'rgba(0, 255, 255, 0.8)',
                    'rgba(255, 170, 0, 0.8)',
                    'rgba(0, 128, 255, 0.8)',
                    'rgba(128, 0, 255, 0.8)',
                    'rgba(255, 102, 0, 0.8)'
                ],
                borderColor: [
                    'rgba(255, 0, 102, 1)',
                    'rgba(0, 255, 255, 1)',
                    'rgba(255, 170, 0, 1)',
                    'rgba(0, 128, 255, 1)',
                    'rgba(128, 0, 255, 1)',
                    'rgba(255, 102, 0, 1)'
                ],
                borderWidth: 2,
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                x: {
                    ticks: {
                        color: '#b0b8c1',
                        font: {
                            size: 12
                        }
                    },
                    grid: {
                        color: 'rgba(0, 255, 255, 0.1)'
                    }
                },
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '能耗 (kW·h)',
                        color: '#00ffff'
                    },
                    ticks: {
                        color: '#b0b8c1'
                    },
                    grid: {
                        color: 'rgba(0, 255, 255, 0.1)'
                    }
                }
            }
        }
    });
}

// 更新显示
function updateDisplay() {
    // 更新总重量
    const totalWeight = trainData.weight.a1 + trainData.weight.b1 + trainData.weight.b2 + trainData.weight.a2;
    document.getElementById('total-weight').textContent = totalWeight.toLocaleString();
    
    // 更新节能模式
    document.getElementById('energy-saving').textContent = trainData.is_energy_saving ? '是' : '否';
    document.getElementById('energy-saving').className = trainData.is_energy_saving ? 
        'data-value text-success' : 'data-value text-warning';
    
    // 更新总能耗
    document.getElementById('total-consumption').textContent = trainData.air_consumption.total.toFixed(1);
    
    // 更新车厢数据
    updateCarData('a1', trainData.temp_humi.a1, trainData.weight.a1);
    updateCarData('b1', trainData.temp_humi.b1, trainData.weight.b1);
    updateCarData('b2', trainData.temp_humi.b2, trainData.weight.b2);
    updateCarData('a2', trainData.temp_humi.a2, trainData.weight.a2);
    
    // 更新环境数据
    document.getElementById('outdoor-temp').textContent = trainData.temp_humi.a1.outdoor_temp;
    document.getElementById('pm25').textContent = trainData.temp_humi.a1.pm25;
    document.getElementById('pmtovc').textContent = trainData.temp_humi.a1.pmtovc;
    document.getElementById('co2').textContent = trainData.temp_humi.a1.co2;
    
    // 更新阀门状态
    updateValveStatus('a1', trainData.valves.a1);
    updateValveStatus('b1', trainData.valves.b1);
    updateValveStatus('b2', trainData.valves.b2);
    updateValveStatus('a2', trainData.valves.a2);
    
    // 更新图表
    updateCharts();
}

// 更新车厢数据
function updateCarData(carId, data, weight) {
    document.getElementById(`${carId}-temp`).textContent = data.temp;
    document.getElementById(`${carId}-humi`).textContent = data.humidity;
    document.getElementById(`${carId}-weight`).textContent = weight;
}

// 更新阀门状态
function updateValveStatus(carId, valveData) {
    const container = document.getElementById(`${carId}-valves`);
    container.innerHTML = '';
    
    // 显示16个阀门状态
    for (let i = 0; i < 16; i++) {
        const isOpen = (valveData.status & (1 << i)) !== 0;
        const valveDiv = document.createElement('div');
        valveDiv.className = `status-indicator ${isOpen ? 'status-online' : 'status-offline'} me-1 mb-1`;
        valveDiv.title = `阀门 ${i + 1}: ${isOpen ? '开启' : '关闭'}`;
        container.appendChild(valveDiv);
    }
    
    // 添加温度信息
    const tempDiv = document.createElement('div');
    tempDiv.className = 'w-100 mt-2';
    tempDiv.innerHTML = `
        <small class="text-muted">
            客室: ${valveData.room_temp}°C | 
            回风: ${valveData.return_air_temp}°C | 
            新风: ${valveData.fresh_air_temp}°C
        </small>
    `;
    container.appendChild(tempDiv);
}

// 更新图表
function updateCharts() {
    const now = new Date();
    const timeStr = now.toLocaleTimeString();
    
    // 更新温度图表
    chartData.temperature.labels.push(timeStr);
    chartData.temperature.a1.push(trainData.temp_humi.a1.temp);
    chartData.temperature.b1.push(trainData.temp_humi.b1.temp);
    chartData.temperature.b2.push(trainData.temp_humi.b2.temp);
    chartData.temperature.a2.push(trainData.temp_humi.a2.temp);
    
    // 保持最近20个数据点
    if (chartData.temperature.labels.length > 20) {
        chartData.temperature.labels.shift();
        chartData.temperature.a1.shift();
        chartData.temperature.b1.shift();
        chartData.temperature.b2.shift();
        chartData.temperature.a2.shift();
    }
    
    temperatureChart.data.labels = chartData.temperature.labels;
    temperatureChart.data.datasets[0].data = chartData.temperature.a1;
    temperatureChart.data.datasets[1].data = chartData.temperature.b1;
    temperatureChart.data.datasets[2].data = chartData.temperature.b2;
    temperatureChart.data.datasets[3].data = chartData.temperature.a2;
    temperatureChart.update();
    
    // 更新能耗图表
    energyChart.data.datasets[0].data = [
        trainData.air_consumption.driver_cab,
        trainData.air_consumption.a1,
        trainData.air_consumption.b1,
        trainData.air_consumption.b2,
        trainData.air_consumption.a2,
        trainData.air_consumption.tail_driver_cab
    ];
    energyChart.update();
}

// 更新时钟
function updateClock() {
    const now = new Date();
    document.getElementById('current-time').textContent = now.toLocaleTimeString();
}

// 模拟数据更新
function simulateDataUpdate() {
    // 模拟温度变化
    trainData.temp_humi.a1.temp += (Math.random() - 0.5) * 2;
    trainData.temp_humi.b1.temp += (Math.random() - 0.5) * 2;
    trainData.temp_humi.b2.temp += (Math.random() - 0.5) * 2;
    trainData.temp_humi.a2.temp += (Math.random() - 0.5) * 2;
    
    // 限制温度范围
    Object.values(trainData.temp_humi).forEach(car => {
        car.temp = Math.max(15, Math.min(30, car.temp));
        car.humidity = Math.max(30, Math.min(70, car.humidity + (Math.random() - 0.5) * 5));
    });
    
    // 模拟能耗变化
    trainData.air_consumption.driver_cab += (Math.random() - 0.5) * 0.1;
    trainData.air_consumption.a1 += (Math.random() - 0.5) * 0.2;
    trainData.air_consumption.b1 += (Math.random() - 0.5) * 0.2;
    trainData.air_consumption.b2 += (Math.random() - 0.5) * 0.2;
    trainData.air_consumption.a2 += (Math.random() - 0.5) * 0.2;
    trainData.air_consumption.tail_driver_cab += (Math.random() - 0.5) * 0.1;
    
    // 确保能耗不为负
    Object.keys(trainData.air_consumption).forEach(key => {
        trainData.air_consumption[key] = Math.max(0, trainData.air_consumption[key]);
    });
    
    // 重新计算总能耗
    trainData.air_consumption.total = Object.values(trainData.air_consumption).reduce((sum, val) => sum + val, 0);
    
    // 模拟重量变化
    trainData.weight.a1 += Math.floor((Math.random() - 0.5) * 100);
    trainData.weight.b1 += Math.floor((Math.random() - 0.5) * 100);
    trainData.weight.b2 += Math.floor((Math.random() - 0.5) * 100);
    trainData.weight.a2 += Math.floor((Math.random() - 0.5) * 100);
    
    // 确保重量不为负
    Object.keys(trainData.weight).forEach(key => {
        trainData.weight[key] = Math.max(0, trainData.weight[key]);
    });
    
    // 模拟阀门状态变化
    Object.values(trainData.valves).forEach(valve => {
        valve.status = Math.floor(Math.random() * 0xFFFF);
        valve.room_temp += (Math.random() - 0.5) * 1;
        valve.return_air_temp += (Math.random() - 0.5) * 1;
        valve.fresh_air_temp += (Math.random() - 0.5) * 1;
        
        // 限制温度范围
        valve.room_temp = Math.max(15, Math.min(30, valve.room_temp));
        valve.return_air_temp = Math.max(15, Math.min(30, valve.return_air_temp));
        valve.fresh_air_temp = Math.max(10, Math.min(25, valve.fresh_air_temp));
    });
    
    // 模拟节能模式切换
    if (Math.random() < 0.1) {
        trainData.is_energy_saving = !trainData.is_energy_saving;
    }
    
    // 添加系统日志
    addSystemLog(`数据更新 - 总重量: ${(trainData.weight.a1 + trainData.weight.b1 + trainData.weight.b2 + trainData.weight.a2).toLocaleString()}kg, 总能耗: ${trainData.air_consumption.total.toFixed(1)}kW·h`);
}

// 添加系统日志
function addSystemLog(message) {
    const logContainer = document.getElementById('system-log');
    const logEntry = document.createElement('div');
    logEntry.className = 'alert alert-info alert-custom py-2 mb-2';
    logEntry.innerHTML = `
        <small>
            <i class="fas fa-info-circle me-2"></i>
            ${new Date().toLocaleTimeString()} - ${message}
        </small>
    `;
    
    logContainer.insertBefore(logEntry, logContainer.firstChild);
    
    // 限制日志数量
    while (logContainer.children.length > 50) {
        logContainer.removeChild(logContainer.lastChild);
    }
}

// 开始实时更新
function startRealTimeUpdates() {
    setInterval(() => {
        fetchDataFromAPI();
    }, 2000); // 每2秒更新一次
}

// 刷新数据
async function refreshData() {
    addSystemLog('手动刷新数据');
    await fetchDataFromAPI();
}

// 从后端API获取数据
async function fetchDataFromAPI() {
    try {
        const response = await fetch('/api/train-data');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        trainData = data;
        updateDisplay();
    } catch (error) {
        console.error('获取数据失败:', error);
        addSystemLog('获取数据失败: ' + error.message);
        // 如果API失败，使用模拟数据
        simulateDataUpdate();
        updateDisplay();
    }
}

// 导出数据功能
async function exportData() {
    try {
        const response = await fetch('/api/export');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        const dataStr = JSON.stringify(data, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        const url = URL.createObjectURL(dataBlob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `train-data-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`;
        link.click();
        URL.revokeObjectURL(url);
        addSystemLog('数据导出完成');
    } catch (error) {
        console.error('导出数据失败:', error);
        addSystemLog('导出数据失败: ' + error.message);
    }
}

// 控制功能
async function sendControlCommand(action, target = null, value = null) {
    try {
        const command = { action };
        if (target) command.target = target;
        if (value !== null) command.value = value;
        
        const response = await fetch('/api/control', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(command)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        if (result.success) {
            addSystemLog(result.message);
        } else {
            addSystemLog('控制指令失败: ' + result.message);
        }
        
        // 刷新数据
        await fetchDataFromAPI();
        
    } catch (error) {
        console.error('发送控制指令失败:', error);
        addSystemLog('发送控制指令失败: ' + error.message);
    }
}

// 温度控制
function setTemperature(carId, temperature) {
    sendControlCommand('set_temperature', carId, temperature);
}

// 切换节能模式
function toggleEnergySaving() {
    sendControlCommand('toggle_energy_saving');
}

// 重置阀门
function resetValves() {
    sendControlCommand('reset_valves');
}

// 添加键盘快捷键
document.addEventListener('keydown', function(event) {
    if (event.ctrlKey && event.key === 'r') {
        event.preventDefault();
        refreshData();
    }
    if (event.ctrlKey && event.key === 'e') {
        event.preventDefault();
        exportData();
    }
    if (event.ctrlKey && event.key === 's') {
        event.preventDefault();
        toggleEnergySaving();
    }
}); 